//
//  ADRefreshView.swift
//  01-微博项目搭建
//
//  Created by Adolph on 15/5/28.
//  Copyright (c) 2015年 Adolph. All rights reserved.
//

import UIKit

class ADRefreshViewControl: UIRefreshControl {
 
    /**
    - sb 开发，先调用 initWithCoder，awakeFromNib（从 sb 加载完成）
    - 纯代码开发，只调用 init()／如果是UIView，会调用 initWithFrame
    */
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareView()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func awakeFromNib() {
    super.awakeFromNib()
        prepareView()
    }
    
    ///准备子视图
    var refreshView: ADRefreshView?
    func prepareView() {
   
        //加载xib
     let rView = NSBundle.mainBundle().loadNibNamed("ADRefreshView", owner: nil, options: nil).last as!ADRefreshView
        addSubview(rView)
        
        //设置自动布局， 一定要将子视图添加到视图中，才能够设置约束
        rView.setTranslatesAutoresizingMaskIntoConstraints(false)
        //实例化可变数组
        var cons = [AnyObject]()
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[rView(137)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["rView": rView])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rView(60)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["rView": rView])
        cons.append(NSLayoutConstraint(item: rView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        self.addConstraints(cons)
        self.refreshView = rView
        //设置 KVO 跟踪位置变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
    }
    deinit {
     //kvo 一定要释放
        self.removeObserver(self, forKeyPath: "frame")
    }
    /**
    1. 跟踪 frame 能够跟踪到下拉表格的情况
    2. 如果刷新控件出现,y值是 负数
    3. 越向下，负得越多
    4. 刷新控件一直在表格上，表格越往下，frame的y值越大
    
    思路：
    1. 拽到一定程度，让指针发生反转
    */
    /// 显示提示标记
    var showTipFlag = false
    ///是否正在加载标记
    var isLoadingFlag = false
   
    
    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {

        //        println(self.frame)
        
        if self.frame.origin.y > 0 {
          return
        }
        //判断是否正在刷新
        if refreshing && !isLoadingFlag {
         //播放动画
            refreshView?.startLoading()
            println("正在加载")
            isLoadingFlag = true
            return
        }
        
        if self.frame.origin.y < -50 && !showTipFlag {
          println("改翻转了")
          showTipFlag = true
          refreshView?.rotateTipIcon(showTipFlag)
        } else if self.frame.origin.y > -50 && showTipFlag {
            println("转回去")
            showTipFlag = false
            refreshView?.rotateTipIcon(showTipFlag)
        }
        
    }
    override func endRefreshing() {
        //结束刷新
        super.endRefreshing()
        //停止动画
        refreshView?.stopLoading()
        //重新设置刷新标记
        isLoadingFlag = false
    }
}

class ADRefreshView: UIView {
    ///下载View
    @IBOutlet weak var tipIcon: UIImageView!
    ///加载View
    @IBOutlet weak var loadingIcon: UIImageView!
    ///提示视图
    @IBOutlet weak var tipView: UIView!
    
    ///旋转tipIcon(箭头)
    private func rotateTipIcon(clockWise:Bool) {
     var angel = CGFloat(M_PI)
        angel += clockWise ? -0.01 : 0.01
        
        // 如果用块代码做一圈的旋转，比较费劲
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angel)
        })
    }
        ///播放旋转动画
    func startLoading() {
     tipView.hidden = true
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        //设置一圈所用的时间
        anim.duration = 0.5
        loadingIcon.layer.addAnimation(anim, forKey: nil)
    }
    ///停止加载
    func stopLoading() {
     //删除动画
        loadingIcon.layer.removeAllAnimations()
        // 回复提示视图
        tipView.hidden = false
    }
    
}